import type { Effect, Reducer } from 'umi';

import { findCurrent } from '@/services/user';

export type CurrentUser = {
  avatar?: string;
  username?: string;
  title?: string;
  group?: string;
  signature?: string;
  tags?: {
    key: string;
    label: string;
  }[];
  ID?: string;
};

export type UserModelState = {
  currentUser?: CurrentUser;
};

export type UserModelType = {
  namespace: 'user';
  state: UserModelState;
  effects: {
    // fetch: Effect;
    fetchCurrent: Effect;
  };
  reducers: {
    saveCurrentUser: Reducer<UserModelState>;
    // changeNotifyCount: Reducer<UserModelState>;
  };
};

const UserModel: UserModelType = {
  namespace: 'user',
  state: {
    currentUser: {},
  },

  effects: {
    // *fetch({payload}, { call, put }) {
    //   const response = yield call(findCurrent(payload.ID));
    //   yield put({
    //     type: 'save',
    //     payload: response,
    //   });
    // },
    *fetchCurrent({ payload }, { call, put }) {
      const response = yield call(findCurrent, payload);
      yield put({
        type: 'saveCurrentUser',
        payload: response?.data,
      });
    },
  },

  reducers: {
    saveCurrentUser(state, action) {
      return {
        ...state,
        currentUser: action.payload || {},
      };
    },
  },
};

export default UserModel;
